package com.lh.java.basic.lock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;


public class TestLock {
	
	
	public static void main(String[] args) {
		ExecutorService exec = Executors.newFixedThreadPool(20);
			
	    for(int i=1;i<20;i++){
	    	Thread my=new MyThread(i);
	    	exec.submit(my);
	    }
		
	}

	
}
class MyThread extends Thread{
	int i;
	ReentrantReadWriteLock reenWriteLock = new ReentrantReadWriteLock();	
	MyThread(int i){
		this.i = i ;
		
	}
	public void run() {
		try {
			System.out.println("i am " + i + "start" );
			WriteLock lock1 = reenWriteLock.writeLock();
			lock1.lock();
			int j = (int) (Math.random() * 10000)/1000;
			System.out.println("i am "+i+"我得到锁，我休息"+j+"秒");
			Thread.sleep(j*1000);			
			lock1.unlock();
			System.out.println("i am "+i+"我释放锁");		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
